import {
  CanActivate,
  ExecutionContext,
  Injectable,
  Logger,
} from '@nestjs/common';
import { Request } from 'express';
import { decrypt } from '../utils/rsa.util';
import { ResponseMsgKey } from '../constants/api-response.constant';

/**
 * @Description 检查请求body参数是否为公钥加密密文并将解密后的明文返回给reuqest.body
 */
@Injectable()
export class ParamDecryptGuard implements CanActivate {
  private readonly logger = new Logger(ParamDecryptGuard.name);
  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      const request = context.switchToHttp().getRequest<Request>();
      const body = request.body;
      if (typeof body !== 'string') throw new Error();
      request.body = decrypt(body);
      this.logger.log(`Body: ${JSON.stringify(request.body)}`);
      return true;
    } catch (error) {
      this.logger.error(JSON.stringify(error.message));
      throw new Error(ResponseMsgKey.PARAM_ERROR);
    }
  }
}
